package org.desktop.web.server.timesheet.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.desktop.web.client.timesheet.service.TimesheetService;
import org.desktop.web.server.util.RpcUtil;
import org.desktop.web.shared.domain.entities.SubProject;
import org.json.JSONArray;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class TimesheetServiceImpl extends RemoteServiceServlet implements
		TimesheetService {

	private String subprojectsInUrl="http://127.0.0.1:8080/timesheet/timesheets/bySubProjectsIn";

	@Override
	public boolean hasSubproject(List<SubProject> subprojects) throws Exception {
		try{
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(subprojects);
		System.out.println(json);
		HttpURLConnection con = RpcUtil.getUrlConnection(new URL(subprojectsInUrl), "POST");
		con.setRequestProperty("Accept", "application/json");
		con.setRequestProperty("Content-Type", "application/octect-stream");
		OutputStream out = con.getOutputStream();
		out.write(json.getBytes());
		System.out.println("qua sugno");
		out.close();
		System.out.println("chiuso stream in output");
		InputStream in = con.getInputStream();
		int code = con.getResponseCode();
		in.close();
		return code==302;//se diverso da 404 esistono record
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		// TODO Auto-generated method stub
	}

}
